import Api from "../constants/Api";
import global from "../global";
import {
    Message
} from "element-ui";
import axios from "@/axios"

export default {
    uploadImg(file) {

        return new Promise(((resolve, reject) => {
            const fileItem = file.name.split(".");
            let fileType = fileItem[fileItem.length - 1].toLowerCase();
            const isImg = global.imgType.includes(fileType);
            if (!isImg) {
                Message.warning(`请上传正确的图片格式`);
                return false;
            }
            let bucketName = "img";

            let fd = new FormData();
            fd.append("file", file);


            let url = Api.fileUpload.replace("{bucketName}", bucketName);
            axios({
                method: "post",
                url: url,
                data: fd,
                headers: {"Content-Type": "multipart/form-data"},
                timeout: 1000 * 60 * 60,
                onUploadProgress: (progressEvent) => {
                    if (progressEvent.lengthComputable) {
                        let perc = Math.round(
                            (progressEvent.loaded / progressEvent.total) * 100
                        );
                        console.log(perc);
                    }
                },
            })
                .then((res) => {
                    if (res.code === 20002) {

                        resolve(res.data.filePath)
                    } else {
                        reject(res.msg)
                    }
                })
                .catch((err) => {
                    reject(err)
                });
        }))
    },
}
